package com.mmz.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.mmz.common.to.SkuEsModel;
import com.mmz.gulimall.search.config.GulimallElasticsearchConfig;
import com.mmz.gulimall.search.constant.EsConstant;
import com.mmz.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品上架服务
 *
 * @author mangmangguai
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        if(CollectionUtils.isEmpty(skuEsModels)){
            return true;
        }
        //保存到es
        //1、给es中建立索引，product，建立好映射关系 之前在kibana中已经设置
        //2、给es中保存这些数据
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            //1、构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);
            //2、放入bulk中
            bulkRequest.add(indexRequest);
        }
        //3、写入ES中
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
        //4、判断写入结果(存在异常b就为true)
        boolean b = bulk.hasFailures();

        //todo 如果批量错误
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架完成：{}", collect);

        return !b;
    }
}
